//
//  HomeAutomation.swift
//  home
//
//  Created by Yun Zeng on 2019/3/10.
//  Copyright © 2019 Yun Zeng. All rights reserved.
//

import Foundation

class HomeAutomation: Codable {
    enum TriggerType: String {
        case leave = "go-home"        // 出门
        case arrive = "leave-home"      // 回家
        case timer = "timer"        // 定时
        case refrigeration = "refrigeration"   // 制冷
        case dehumidify = "dehumidify"         // 除湿
        case dehumidifyOff = "dehumidify-off" // 传感器
        case motionTrigger = "motion-trigger"   // 运动传感器触发
        case clickTrigger = "click-trigger"     // 情景按键触发
        case unknown
    }
    
    var id: String
    var title: String = ""
    var subtitle: String = ""
    var isEnable: Bool = true
    
    var scenes: [String]?
    var actions: [HomeAction]?
    var type: String = ""
    
    var events: [AutomationTrigger]
    var conditions: [AutomationCondition]?
    
    init(id: String, event: AutomationTrigger) {
        self.id = id
        self.events = [AutomationTrigger]()
        self.events.append(event)
    }
    
    private enum CodingKeys: String, CodingKey {
        case id
        case title
        case subtitle
        case isEnable = "enable"
        case events
        case conditions
        case type
        case scenes
        case actions
    }
}

extension HomeAutomation: CustomStringConvertible {
    var description: String {
        let data = try! JSONEncoder().encode(self)
        return String(data: data, encoding: .utf8)!
    }
}

class HomeAutomationManager: Codable {
    var automations: [HomeAutomation]
    init(automations: [HomeAutomation]) {
        self.automations = automations
    }
    
    public func encode(to encoder: Encoder) throws {
        var container = encoder.singleValueContainer()
        try container.encode(self.automations)
    }
    
    public required convenience init(from decoder: Decoder) throws {
        let container = try decoder.singleValueContainer()
        let automations = try container.decode([HomeAutomation].self)
        self.init(automations: automations)
    }
}

extension HomeAutomationManager: CustomStringConvertible {
    var description: String {
        let data = try! JSONEncoder().encode(self)
        return String(data: data, encoding: .utf8)!
    }
}



